package cn.jbolt.admin.role;

import cn.jbolt.admin.permission.PermissionService;
import cn.jbolt.admin.user.UserService;
import cn.jbolt.core.api.JBoltApiBaseController;
import cn.jbolt.core.api.httpmethod.JBoltHttpGet;
import cn.jbolt.core.api.httpmethod.JBoltHttpPost;
import cn.jbolt.core.base.JBoltMsg;
import cn.jbolt.core.cache.JBoltRoleCache;
import cn.jbolt.core.model.Permission;
import cn.jbolt.core.model.Role;
import cn.jbolt.core.model.base.JBoltBaseModel;
import cn.jbolt.core.para.JBoltNoUrlPara;
import cn.jbolt.core.permission.CheckPermission;
import cn.jbolt.core.permission.UnCheck;
import cn.jbolt.core.permission.UnCheckIfSystemAdmin;
import cn.jbolt.core.service.JBoltRolePermissionService;
import cn.jbolt.core.service.JBoltRoleService;
import cn.jbolt.core.service.base.JBoltBaseService;
import cn.jbolt.extend.permission.PermissionKey;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.core.paragetter.Para;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.List;
import java.util.Set;

@UnCheckIfSystemAdmin
@CheckPermission(PermissionKey.ROLE)
@Path("/api/admin/role")
public class RoleAdminController extends JBoltApiBaseController {

    @Inject
    private JBoltRoleService service;
    @Inject
    JBoltRolePermissionService rolePermissionService;

    @Inject
    PermissionService permissionService;
    @Inject
    UserService userService;

    @Override
    protected JBoltBaseService<? extends JBoltBaseModel<?>> getModelService() {
        return service;
    }

    /**
     * 单个详情
     */
    @JBoltHttpGet
    public void index() {
        renderJBoltApiRet(findModelById());
    }

    /**
     * 分页条件查询数据源
     */
    @JBoltHttpGet
    public void datas() {
        renderJBoltApiSuccessWithData(service.getAllRoleTreeDatas());
    }

    /**
     * select数据源options
     */
    @UnCheck
    @JBoltHttpGet
    public void options() {
        renderJBoltApiSuccessWithData(service.getAllRoleTreeDatas());
    }



    /**
     * 保存
     */
    @Before(Tx.class)
    @JBoltHttpPost
    public void save(@Para("") Role role) {
        renderJBoltApiRet(service.save(role));
    }

    /**
     * 更新
     */
    @Before(Tx.class)
    @JBoltHttpPost
    public void update(@Para("")Role role) {
        renderJBoltApiRet(service.update(role));
    }

    /**
     * 删除
     */
    @Before(Tx.class)
    @JBoltHttpGet
    public void delete() {
        renderJBoltApiRet(service.delete(getId()));
    }

    /**
     * 角色下用户数据查询
     * @param page
     * @param pageSize
     * @param roleId
     */
    @JBoltHttpGet
    public void users(@Para(value = PAGE_PARAM_NAME,defaultValue = "1")Integer page,@Para(value = PAGESIZE_PARAM_NAME,defaultValue = "15")Integer pageSize,@Para("roleId")Long roleId) {
        if(notOk(roleId)){
            renderJBoltApiFail("参数异常:roleId");
            return;
        }
        renderJBoltApiSuccessWithData(userService.paginateUsersByRoleId(page,pageSize,roleId));
    }

    /**
     * 读取角色应该分配的所有权限以及处理是否选中的数据
     */
    @JBoltHttpGet
    public void permissionSettingDatas(){
        Long roleId=getId();
        if(notOk(roleId)) {
            renderJBoltApiFail(JBoltMsg.PARAM_ERROR);
            return;
        }
        Role role= JBoltRoleCache.me.get(roleId);
        if(role==null) {
            renderJBoltApiFail("角色信息不存在");
            return;
        }
        List<Permission> permissions=null;
        if(isOk(role.getPid())) {
            permissions=permissionService.getParentPermissionsWithLevel(role.getPid());
            if(notOk(permissions)){
                renderJBoltApiFail("父级角色["+JBoltRoleCache.me.getName(role.getPid())+"]尚未分配任何权限资源");
                return;
            }
        }else {
            permissions=permissionService.getAllPermissionsWithLevel();
            if(notOk(permissions)){
                renderJBoltApiFail("系统尚未添加任何权限资源");
                return;
            }
        }

        Set<String> keySet = rolePermissionService.getPermissionsKeySetByRoles(roleId.toString());
        if(keySet!=null && !keySet.isEmpty()){
            processItemsChecked(permissions,keySet);
        }
        renderJBoltApiSuccessWithData(permissions);
    }

    private void processItemsChecked(List<Permission> permissions,Set<String> keySet){
        permissions.forEach(permission -> {
            if(keySet.contains(permission.getPermissionKey())){
                permission.set("is_checked",true, true);
            }
            if(isOk(permission.getItems())){
                processItemsChecked(permission.getItems(),keySet);
            }

        });
    }


    /**
     * 提交角色分配资源变更
     * @param roleId
     * @param permissions
     */
    @Before(Tx.class)
    @JBoltHttpPost
    public void submitPermissions(@Para("roleId")Long roleId,@Para("permissions")String permissions){
        renderJBoltApiRet(rolePermissionService.doSubmit(roleId,permissions));
    }

    /**
     *  获取角色已经设置的资源
     */
    @JBoltHttpGet
    public void getCheckeds(){
        renderJBoltApiSuccessWithData(rolePermissionService.getListByRole(getId()));
    }
    /**
     * 根据角色ID去清空此角色绑定的所有权限
     */
    @Before(Tx.class)
    @JBoltHttpGet
    public void clearPermissions() {
        renderJBoltApiRet(rolePermissionService.deleteByRole(getId()));
    }

    /**
     * 根据角色ID去清空此角色绑定的所有用户
     */
    @Before(Tx.class)
    @JBoltHttpGet
    public void clearUsers() {
        renderJBoltApiRet(userService.clearUsersByRole(getId()));
    }

    /**
     * 移除一个角色下的指定ID的user用户
     */
    @Before({Tx.class, JBoltNoUrlPara.class})
    @JBoltHttpGet
    public void removeUser(@Para("roleId")Long roleId,@Para("userId")Long userId){
        renderJBoltApiRet(userService.deleteUserRole(userId,roleId));
    }

}
